<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/vaadin-dialog/vaadin-dialog.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-input/paper-input-error.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../../bower_components/vaadin-icons/vaadin-icons.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions-behavior.html">
<link rel="import" href="cloud-edit.html">
<link rel="import" href="other-cloud-add-machine.html">
<link rel="import" href="../tags/tags-form.html">
<link rel="import" href="../helpers/xterm-dialog.html">
<link rel="import" href="../helpers/dialog-element.html">

<dom-module id="cloud-actions">
  <template>
    <style include="shared-styles">
      mist-list-actions {
        width: 100%;
      }

      vaadin-dialog#renameDialog {
        max-width: 350px;
      }

      vaadin-dialog#credentialsDialog,
      vaadin-dialog#addhostsDialog,
      vaadin-dialog#dnsDialog {
        max-width: 650px;
      }

      div.button {
        margin: 24px 0 0 0;
        display: flex;
        justify-content: flex-end;
      }
    </style>

    <iron-ajax id="cloudEditAjaxRequest" url="/api/v1/clouds/[[cloud.id]]" method="PUT" on-response="_handleCloudEditAjaxResponse" on-error="_handleCloudEditAjaxError"></iron-ajax>
    <iron-ajax id="cloudDeleteAjaxRequest" url="/api/v1/clouds/[[cloud.id]]" method="DELETE" on-response="_handleCloudDeletionAjaxResponse" on-error="_handleCloudDeletionAjaxError"></iron-ajax>

    <vaadin-dialog id="renameDialog" theme="mist-dialog" with-backdrop>
      <template>
        <h3>Rename Cloud</h3>
        <div style="margin-bottom: 16px;">
            <paper-input label="Title" value="{{newCloud.title}}" autofocus tabindex="0"></paper-input>
            <div class="button">
                <paper-button id="rename-cloud" dialog-confirm disabled$="[[!formReady]]" on-tap="_changeTitle" class="blue">Save Title</paper-button>
            </div>
        <div>
      </template>
    </vaadin-dialog>

    <vaadin-dialog id="credentialsDialog" theme="mist-dialog" with-backdrop>
      <template>
        <h3>Edit Credentials</h3>
        <div style="margin-bottom: 16px;">
          <cloud-edit cloud="[[cloud]]" clouds="[[model.clouds]]" keys="[[model.keysArray]]"></cloud-edit>
        </div>
      </template>
    </vaadin-dialog>

    <vaadin-dialog id="addhostsDialog" theme="mist-dialog" with-backdrop>
      <template>
        <h3>Add Host</h3>
        <div>
          <other-cloud-add-machine cloud="[[cloud]]" keys="[[model.keysArray]]"></other-cloud-add-machine>
        </div>
      </template>
    </vaadin-dialog>

    <iron-ajax id="cloudDeleteAjaxRequest" url="/api/v1/clouds/[[cloud.id]]" method="DELETE" on-response="_handleCloudDeletionAjaxResponse"
      on-error="_handleCloudDeletionAjaxError"></iron-ajax>
    <dialog-element id="confirm"></dialog-element>
    <tags-form id="tagsdialog" model="[[model]]" items="[[items]]" type="[[resourceType]]"></tags-form>
    <iron-ajax id="request" handle-as="json" loading="{{loadingData}}" on-response="handleResponse" on-error="handleError"></iron-ajax>

    <slot>
        <mist-list-actions actions=[[actions]]></mist-list-actions>
    </slot>

  </template>
  <script>
    CLOUD_ACTIONS = {
      'tag': {
        'name': 'tag',
        'icon': 'label',
        'confirm': true,
        'multi': true
      },
      'rename': {
        'name': 'rename',
        'icon': 'editor:mode-edit',
        'confirm': false,
        'multi': true
      },
      'edit_credentials': {
        'name': 'edit credentials',
        'icon': 'icons:lock-outline',
        'confirm': false,
        'multi': true
      },
      'add_hosts': {
        'name': 'add host',
        'icon': 'hardware:computer',
        'confirm': false,
        'multi': false
      },
      'delete': {
        'name': 'delete',
        'icon': 'delete',
        'confirm': true,
        'multi': true
      }
    };

    Polymer({
      is: 'cloud-actions',

      behaviors: [MistListActionsBehavior],

      properties: {
        model: {
            type: Object
        },
        items: {
          type: Array,
          value: function () { return [] }
        },
        cloud: {
          type: Object,
          computed: '_computeCloud(items, items.length)'
        },
        actions: {
          type: Array,
          value: function () { return [] },
          notify: true
        },
        resourceType: {
          type: String,
          value: 'cloud'
        },
        inSingleView: {
          type: Boolean,
          reflectToAttribute: true
        },
        newCloud: {
          type: Object,
          computed: '_computeNewCloud(cloud)'
        },
        sendingData: {
          type: Boolean,
          value: false
        },
        formReady: {
          type: Boolean,
          computed: '_computeFormReady(cloud.title, newCloud.title, sendingData)'
        }
      },

      listeners: {
        'select-action': 'selectAction',
        'confirmation': 'confirmAction',
        'close-rename-dialog': 'closeRenameDialog',
        'add-input': 'closeDialog',
        'response': 'closeDialogs',
        'cancel': 'closeDialogs'
      },

      attached: function () {
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "POST";
      },

      closeRenameDialog: function (e) {
        this.$.renameDialog.opened = false;
      },

      computeItemActions: function (cloud) {
        var arr = [];
        if (cloud) {
          arr.push('tag');
          arr.push('rename');
          if (this._isBareMetal(cloud.provider))
            arr.push('add_hosts');
          if (!this._isBareMetal(cloud.provider))
            arr.push('edit_credentials');
          arr.push('delete');
        }
        return arr;
      },

      _isBareMetal: function (provider) {
        return provider == 'bare_metal';
      },

      computeActionListDetails: function (actions) {
        var ret = [];
        for (var i = 0; i < actions.length; i++) {
          ret.push(CLOUD_ACTIONS[actions[i]]);
        }
        return ret;
      },

      confirmAction: function (e) {
        if (e.detail.confirmed)
          this.performAction(this.action, this.items);
      },

      selectAction: function (e) {
        if (this.items.length) {
          var action = e.detail.action;
          this.set('action', action);
          // console.log('perform action mist-action', this.items);
          if (action.confirm && action.name == 'delete' && this.items.length == 1) {
            this._showDialog({
              title: 'Delete cloud?',
              body: "Deleting a cloud can not be undone.",
              danger: true,
              list: this._makeList(this.items, 'title'),
              reason: "cloud.delete"
            });
          } else if (action.confirm && action.name != 'tag') {
            var plural = this.items.length == 1 ? '' : 's',
              count = this.items.length > 1 ? this.items.length + ' ' : '';
            //this.tense(this.action.name) + " " + this.resourceType + "s can not be undone. 
            this._showDialog({
              title: this.action.name + ' ' + count + this.resourceType + plural + '?',
              body: "You are about to " + this.action.name + " " + this.items.length + " " + this.resourceType +
                plural + ".",
              list: this._makeList(this.items, 'title'),
              action: action.name,
              danger: true,
              reason: this.resourceType + "." + this.action.name
            });
          } else if (action.name == 'tag') {
            this.$.tagsdialog._openDialog();
          } else if (action.name == 'edit credentials') {
            this.$.credentialsDialog.opened = true;
          } else if (action.name == 'add host') {
            this.$.addhostsDialog.opened = true;
          } else {
            this.performAction(this.action, this.items);
          }
        }
      },

      openEditDialog: function () {
        this.$.credentialsDialog.opened = true;
      },

      closeDialog: function () {
        // console.log('closeDialog');
        this.$.credentialsDialog.opened = false;
      },

      closeDialogs: function () {
        this.$.renameDialog.opened = false;
        this.$.credentialsDialog.opened = false;
        this.$.addhostsDialog.opened = false;
        this.$.cloudDeleteAjaxRequest.opened = false;
      },

      _showDialog: function (info) {
        var dialog = this.shadowRoot.querySelector('dialog-element');
        if (info) {
          for (var i in info) {
            dialog[i] = info[i];
          }
        }
        dialog._openDialog();
      },

      performAction: function (action, items) {
        if (action.name == 'rename') {
          this.$.renameDialog.opened = true;
        } else if (action.name == 'delete') {
          var l = items.length;
          for (var i=0;i<l;i++) {
            this._deleteCloud();
            this.set('items', items.splice(1));
          }
        }
      },

      _deleteCloud: function () {
        this.$.cloudDeleteAjaxRequest.headers["Content-Type"] = 'application/json';
        this.$.cloudDeleteAjaxRequest.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.cloudDeleteAjaxRequest.generateRequest();
      },

      handleResponse: function (e) {
        this.dispatchEvent(new CustomEvent('action-finished', { bubbles: true, composed: true, detail: {
          success: true
        } }));

        if (this.$.request && this.$.request.body && this.$.request.body.action)
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail:  {
            msg: 'Action: ' + this.$.request.body.action + ' successfull',
            duration: 3000
          } }));
      },

      _handleCloudDeletionAjaxResponse: function (e) {
        var title = '';
        if (this.cloud && this.cloud.title)
          title = this.cloud.title;

        if (this.__dataHost.tagName == 'CLOUD-PAGE')
          this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail: {
            url: '/'
          } }));

        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {
          msg: 'Cloud ' + title + ' was deleted',
          duration: 3000
        } }));

      },
      _handleCloudDeletionAjaxError: function (e) {
        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {
          msg: 'There was an error deleting ' + this.cloud.title + '.',
          duration: 3000
        } }));

      },

      handleError: function (e) {
        // console.log(e.detail.request.xhr.statusText);
        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {
          msg: 'Error: ' + e.detail.request.xhr.status + " " + e.detail.request.xhr.statusText,
          duration: 5000
        } }));

      },

      _makeList: function (items, property) {
        if (items && items.length)
          return items.map(function (item) {
            return item[property];
          });
      },

      _computeCloud: function (items) {
        if (this.items.length > 0)
          return this.items[0];
      },

      _computeNewCloud: function(cloud) {
        if (cloud)
          return {
            title: this.cloud.title
          }
      },

      _computeIsEnabled: function(enabled) {
        return enabled;
      },

      _computeFormReady: function(title, newTitle, sendingData) {
        var formReady = false;
        if (newTitle && newTitle != title) {
          formReady = true;
        }

        if (sendingData) {
          formReady = false;
        }
        return formReady;
      },

      _changeTitle: function() {
        this.$.cloudEditAjaxRequest.headers["Content-Type"] = 'application/json';
        this.$.cloudEditAjaxRequest.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.cloudEditAjaxRequest.body = {
          new_name: this.newCloud.title
        };
        this.$.cloudEditAjaxRequest.generateRequest();
        this.set('sendingData', true);
        this.set('opened', false);
      },

      _handleCloudEditAjaxResponse: function() {
        this.set('sendingData', false);
      }
    });
  </script>
</dom-module>